package top.sehnsucht.dao.impl;

import org.apache.log4j.Logger;
import top.sehnsucht.dao.UserDao;
import top.sehnsucht.entity.User;
import top.sehnsucht.util.DBUtil;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Author: Cai
 * @CreateTime: 2021/12/21
 */
public class UserDaoImpl implements UserDao {
    private Logger logger = Logger.getLogger(this.getClass());

    @Override
    public boolean selectUser(User user) {
        Connection conn = null;
        PreparedStatement ps = null;
        FileInputStream in = null;
        ResultSet rs = null;
        try {
            conn = DBUtil.getConn();
            String sql = "select username,passwd from user";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery(sql);
            while (rs.next()) {
                String username = rs.getString(1);
                String password = rs.getString(2);
                if (user.getUsername().equals(username) && user.getPasswd().equals(password)) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConn(conn);
            if (null != ps) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    @Override
    public int selectUserId(User user) {
        Connection conn = null;
        PreparedStatement ps = null;
        FileInputStream in = null;
        ResultSet rs = null;
        try {
            conn = DBUtil.getConn();
            String sql = "select userId,username,passwd from user";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery(sql);
            while (rs.next()) {
                Integer userId = rs.getInt(1);
                String username = rs.getString(2);
                String password = rs.getString(3);
                if (user.getUsername().equals(username) && user.getPasswd().equals(password)) {
                    return userId;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConn(conn);
            if (null != ps) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return -1;
    }
}
